package com.dawnClass.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.dawnClass.VO.ChapterVideoVO;
import com.dawnClass.VO.CourseReviewConsumerVO;
import com.dawnClass.VO.VideoRateVO;
import com.dawnClass.mapper.*;
import com.dawnClass.pojo.*;
import com.dawnClass.service.CourseService;
import com.dawnClass.util.ServiceResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class CourseServiceImpl implements CourseService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private ChapterMapper chapterMapper;

    @Autowired
    private VideoMapper videoMapper;

    @Autowired
    private CourseReviewMapper courseReviewMapper;

    @Autowired
    private ConsumerMapper consumerMapper;

    @Autowired
    private ConsumerCourseMapper consumerCourseMapper;

    @Autowired
    private LearningRateMapper learningRateMapper;

    /**
     * 1. 新上好课 课程数据
     * @return
     */
    @Override
    public ServiceResponse xinshanghaokeCourse(){
        CourseExample courseExample = new CourseExample();
        List<Course> courseList = null;

        //设置新上好课名称
        String key = "xinshanghaokeCourse";

        //判断redis有无数据
        ValueOperations valueOperations = redisTemplate.opsForValue();
        if (valueOperations.getOperations().hasKey(key)){
            System.out.println("redis有缓存读取");
            courseList = (List<Course>) valueOperations.get(key);
        }else{
            System.out.println("redis无缓存读取，从数据库读取并写入redis");
            courseExample.setOrderByClause("course_price asc");
            PageHelper.startPage(1,8);
            courseList = courseMapper.selectByExampleWithBLOBs(courseExample);
            valueOperations.set(key,courseList,3, TimeUnit.MINUTES);
        }

        return ServiceResponse.getSuccess(courseList);
    }

    /**
     * 2. 进站必学 课程数据
     * @return
     */
    @Override
    public ServiceResponse jinzhanbixueCourse(){
        CourseExample courseExample = new CourseExample();
        List<Course> courseList = null;

        //设置新上好课名称
        String key = "jinzhanbixueCourse";

        //判断redis有无数据
        ValueOperations valueOperations = redisTemplate.opsForValue();
        if (valueOperations.getOperations().hasKey(key)){
            System.out.println("redis有缓存读取");
            courseList = (List<Course>) valueOperations.get(key);
        }else{
            System.out.println("redis无缓存读取，从数据库读取并写入redis");
            courseExample.setOrderByClause("course_learn_number desc");
            PageHelper.startPage(1,8);
            courseList = courseMapper.selectByExampleWithBLOBs(courseExample);
            valueOperations.set(key,courseList,3, TimeUnit.MINUTES);
        }
        return ServiceResponse.getSuccess(courseList);
    }

    /**
     * 3. 限时拼团 课程数据
     * @return
     */
    @Override
    public ServiceResponse xianshipintuanCourse() {
        CourseExample example = new CourseExample();
        List<Course> courseList = null;

        //设置新上好课名称
        String key = "xianshipintuanCourse";

        //判断redis有无数据
        ValueOperations valueOperations = redisTemplate.opsForValue();
        if (valueOperations.getOperations().hasKey(key)){
            System.out.println("redis有缓存读取");
            courseList = (List<Course>) valueOperations.get(key);
        }else{
            System.out.println("redis无缓存读取，从数据库读取并写入redis");
            example.setOrderByClause("course_learn_number desc");
            PageHelper.startPage(1,4);
            courseList = courseMapper.selectByExampleWithBLOBs(example);
            valueOperations.set(key,courseList,3, TimeUnit.MINUTES);
        }

        return ServiceResponse.getSuccess(courseList);
    }

    /**
     * 获取课程搜索页面所有课程
     * @param pagenum 当前页码
     * @param a 筛选条件1
     * @param b 筛选条件2
     * @param c 筛选条件3
     * @return
     */
    @Override
    public ServiceResponse getAllCourse(Integer pagenum , String a , String b , String c) {
        PageHelper.startPage(pagenum,4);
        CourseExample example = new CourseExample();
        CourseExample.Criteria criteria = example.createCriteria();
//        if (a != "")
//            criteria.andCourseDifficultyEqualTo(a);
//        if (b != "")
//            criteria.andCourseDifficultyEqualTo(b);
        if (c != "")
            criteria.andCourseDifficultyEqualTo(c);
        List<Course> courses = courseMapper.selectByExampleWithBLOBs(example);
        PageInfo<Course> pageInfo = new PageInfo<>(courses);
        if (courses != null)
            return ServiceResponse.getSuccess(pageInfo);
        else
            return ServiceResponse.getFail(null);
    }


    /**
     * 获取课程搜索页面所有课程
     * @param courseName 关键字
     * @param a 筛选条件1
     * @param b 筛选条件2
     * @param c 筛选条件3
     * @return
     */
    @Override
    public ServiceResponse getAllCourseLike(String courseName , String a , String b , String c) {
        PageHelper.startPage(1,4);
        CourseExample example = new CourseExample();
        CourseExample.Criteria criteria = example.createCriteria();
//        if (a != "")
//            criteria.andCourseDifficultyEqualTo(a);
//        if (b != "")
//            criteria.andCourseDifficultyEqualTo(b);
        if (c != "")
            criteria.andCourseDifficultyEqualTo(c);
        criteria.andCourseNameLike("%"+courseName+"%");
        List<Course> courses = courseMapper.selectByExampleWithBLOBs(example);
        System.out.println(courses.get(0));
        PageInfo<Course> pageInfo = new PageInfo<>(courses);
        if (courses != null)
            return ServiceResponse.getSuccess(pageInfo);
        else
            return ServiceResponse.getFail(null);
    }

    /**
     * 通过课程id获取课程详细信息
     * @param courseId 课程id号
     * @return 返回封装了获取结果的ServiceResponse对象
     */
    @Override
    public ServiceResponse getCourseByCourseId(Integer courseId) {
        Course course = courseMapper.selectByPrimaryKey(courseId);
        if (course != null)
            return ServiceResponse.getSuccess(course);
        else
            return ServiceResponse.saveFail(null);
    }

    /**
     * 通过课程id获取课程章节信息
     * @param courseId 课程id
     * @return 返回封装了获取结果的ServiceResponse对象
     */
    @Override
    public ServiceResponse getChapterInfo(Integer consumerId,Integer courseId) {
        List<ChapterVideoVO> vos = new ArrayList<>();
        ChapterExample chapterExample = new ChapterExample();
        chapterExample.createCriteria().andCourseIdEqualTo(courseId);
        List<Chapter> chapters = chapterMapper.selectByExample(chapterExample);

        //通过章节id查询该章节中的video
        for (Chapter chapter : chapters){

            //查询该章节所有Video
            VideoExample videoExample = new VideoExample();
            videoExample.createCriteria().andChapterIdEqualTo(chapter.getChapterId());
            List<Video> videos = videoMapper.selectByExample(videoExample);

            //声明videoRateVOS接受章节中的视频和进度信息
            List<VideoRateVO> videoRateVOS = new ArrayList<>();

            //遍历videos,查询章节是否有学习进度
            for (Video video:videos){

                //查询当前用户是否在当前课程存在学习进度
                LearningRate learningRate = null;
                LearningRateExample rateExample = new LearningRateExample();
                rateExample.createCriteria()
                        .andConsumerIdEqualTo(consumerId)
                        .andVideoIdEqualTo(video.getVideoId());
                List<LearningRate> learningRates = learningRateMapper.selectByExample(rateExample);

                //如果查到该课程学习进度，对其进行封装
                if (learningRates.size()>0)
                    learningRate = learningRates.get(0);
                videoRateVOS.add(new VideoRateVO(video,learningRate));
            }

            //将章节和视频封装成一个vo加入vos
            vos.add(new ChapterVideoVO(chapter,videoRateVOS));
        }
        if (vos != null)
            return ServiceResponse.getSuccess(vos);
        else
            return ServiceResponse.getFail(null);
    }

    /**
     * 根据课程id查询该课程的评论
     * @param courseId 课程id
     * @return 评论和发布评论的用户
     */
    @Override
    public ServiceResponse getReviewByCourseId(Integer courseId) {
        List<CourseReviewConsumerVO> vos = new ArrayList<>();
        CourseReviewExample reviewExample = new CourseReviewExample();
        reviewExample.createCriteria().andCourseIdEqualTo(courseId);
        List<CourseReview> reviews = courseReviewMapper.selectByExampleWithBLOBs(reviewExample);

//      通过章节id查询该章节中的review详情
        for (CourseReview review : reviews){
            Consumer consumer = consumerMapper.selectByPrimaryKey(review.getConsumerId());
            vos.add(new CourseReviewConsumerVO(review,consumer));
        }
        if (vos != null)
            return ServiceResponse.getSuccess(vos);
        else
            return ServiceResponse.getFail(null);
    }

    /**
     * 查询用户是否购买当前课程
     * @param consumer
     * @param courseId
     * @return
     */
    public ServiceResponse getCoursePurchaseStatus(Integer consumer , Integer courseId){

        ConsumerCourseExample example = new ConsumerCourseExample();
        example.createCriteria().andConsumerIdEqualTo(consumer).andCourseIdEqualTo(courseId);
        List<ConsumerCourse> purchases = consumerCourseMapper.selectByExample(example);
        System.out.println("查询结果"+purchases);
        if (purchases.size()>0){
            return ServiceResponse.getSuccess("Purchased");
        }
        return ServiceResponse.getFail("Not purchased");
    }

}
